package com.suse.warmstill.common.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.suse.warmstill.common.enums.ResponseEnum;
import com.suse.warmstill.common.exception.SystemException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class JwtUtil {


    /**
     * 用户登录成功后生成Jwt
     * 使用Hs256算法  私匙使用用户密码
     *
     * @param ttlMillis jwt过期时间
     * @return
     */
    public static String createJWT(long ttlMillis, Long userId) {
        String key = "com.suse.warmstill";
        ttlMillis = ttlMillis * 1000 * 60 * 30;
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder builder = Jwts.builder()
                .setId(userId.toString())
                .setIssuedAt(now)
                .signWith(signatureAlgorithm, key);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            //设置过期时间
            builder.setExpiration(exp);
        }
        return builder.compact();
    }


    /**
     * Token的解密
     *
     * @param token 加密后的token
     * @return
     */
    public static Long getUserId(String token) {

        String key = "com.suse.warmstill";
        //签名秘钥，和生成的签名的秘钥一模一样
        Claims claims = null;
        //得到DefaultJwtParser
        try {
            claims = Jwts.parser()
                    //设置签名的秘钥
                    .setSigningKey(key)
                    //设置需要解析的jwt
                    .parseClaimsJws(token).getBody();
            /*
             * 校验是否过期
             * */
            final Date now = new Date();
            final Date expiration = claims.getExpiration();


            if (now.after(expiration)) {
                log.error(ResponseEnum.LOGIN_TOKEN_EXPIRE.getMsg());
                throw new SystemException(ResponseEnum.LOGIN_TOKEN_EXPIRE.getCode(), ResponseEnum.LOGIN_TOKEN_EXPIRE.getMsg());
            }


        } catch (Exception exception) {
            log.error(ResponseEnum.LOGIN_TOKEN_ERROR.getMsg());
            throw new SystemException(ResponseEnum.LOGIN_TOKEN_ERROR.getCode(), ResponseEnum.LOGIN_TOKEN_ERROR.getMsg());
        }

        return Long.valueOf(claims.getId());
    }


}
